package org.example.diet_compass.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.example.diet_compass.domain.Cart;
import org.example.diet_compass.domain.OrderItems;
import org.example.diet_compass.domain.Orders;
import org.example.diet_compass.dto.CartParam;
import org.example.diet_compass.dto.OrderListResultDto;
import org.example.diet_compass.dto.OrderQueryParam;
import org.example.diet_compass.dto.OrdersDto;
import org.example.diet_compass.resp.Result;
import org.example.diet_compass.resp.ResultCodeEnum;
import org.example.diet_compass.service.CartService;
import org.example.diet_compass.service.GoodsService;
import org.example.diet_compass.service.OrderItemsService;
import org.example.diet_compass.service.OrdersService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Archer_hui
 * @version 1.0
 * @Date 2025/3/16 22:23
 */
@RestController
@RequestMapping("/order")
@Tag(description = "用于处理订单的控制器", name = "订单控制器")
public class OrderController {
    @Resource
    OrdersService ordersService;
    @Resource
    OrderItemsService orderItemsService;
    @Resource
    CartService cartService;
    @Resource
    GoodsService goodsService;


    @PostMapping("/post-order/{userId}")
    @Operation(summary = "订单提交api")
    @Transactional
    public Result<Void> postOrder(@PathVariable(name = "userId") Integer userId) {
        //创建订单
        Orders orders = new Orders(null, userId, null, 0.0, "未完成");
        //保存订单
        ordersService.save(orders);
        //获得订单id
        Integer orderId = ordersService.getOrderIdByUserIdAndState(userId, "未完成");
        //获取当前用户已经勾选的购物车内容
        List<Cart> cartSelectedList = cartService.getGoodsByUserIdAndSelected(userId);
        if (cartSelectedList.isEmpty()) {
            return Result.build(null, ResultCodeEnum.PRODUCT_CART_EMPTY);
        }
        Double[] totalPriceHolder = {0.0};
        cartSelectedList.forEach(cart -> {
            //从购物车返回的属性里抽取字段
            String goodId = cart.getGoodId();
            Integer count = cart.getCount();
            //创建订单-商品对象
            OrderItems orderItem = new OrderItems(null, orderId, goodId, count);
            //保存到order-item表中 记录此次订单存储的商品
            orderItemsService.save(orderItem);
            //根据商品id获得商品单价
            Double goodPrice = goodsService.getGoodPriceById(goodId);
            //计算总价
            totalPriceHolder[0] += goodPrice * count;
        });
        //清除购物车已经完成的记录
        cartService.removeByUserIdAndSelected(userId);
        //重新获取订单，更新总价之后存储回去
        Orders order = ordersService.getById(orderId);
        order.setTotalAmount(totalPriceHolder[0]);
        order.setStatus("已完成");
        ordersService.saveOrUpdate(order);
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }

    @Transactional
    @PostMapping("/order-direct-purchase")
    @Operation(summary = "直接购买的api")
    public Result<Void> cartDirectPurchase(@RequestBody CartParam cartParam) {
        int userId = cartParam.getUserId();
        String goodId = cartParam.getGoodId();
        Double goodPrice = goodsService.getGoodPriceById(goodId);
        int count = cartParam.getCount();
        Orders orders = new Orders(null, userId, null, goodPrice, "立即购买");
        ordersService.save(orders);
        Integer orderId = ordersService.getOrderIdByUserIdAndState(userId, "立即购买");
        ordersService.updateOrderState(orderId, "已完成");
        orderItemsService.save(new OrderItems(null, orderId, goodId, count));

        return Result.build(null, ResultCodeEnum.SUCCESS);
    }

    @PostMapping("/get-order-by-state")
    @Operation(summary = "根据不同的状态分页获取订单记录")
    public Result<OrderListResultDto> getOrdersByState(@RequestBody OrderQueryParam orderQueryParam) {
        int userId = orderQueryParam.getUserId();
        int currentPage = orderQueryParam.getCurrentPage();
        int pageSize = orderQueryParam.getPageSize();
        String status = orderQueryParam.getOrderState();
        OrderListResultDto ordersByPage = ordersService.getOrdersByPage(currentPage, pageSize, userId, status);
        if (ordersByPage == null) {
            return Result.build(null, ResultCodeEnum.ORDER_RECORD_NULL);
        }
        return Result.build(ordersByPage, ResultCodeEnum.SUCCESS);
    }

    @GetMapping("/get-order-by-id")
    @Operation(summary = "根据订单id获取订单的详情")
    public Result<OrdersDto> getOrderResultById(@RequestParam("userId") Integer userId,
                                                @RequestParam("orderId") Integer orderId) {
        OrdersDto ordersDto = ordersService.getOrderDetailByUserIdAndOrderId(userId, orderId);
        return Result.build(ordersDto, ResultCodeEnum.SUCCESS);
    }

    @DeleteMapping("/delete-order-by-id/{id}")
    @Operation(summary = "根据订单id删除订单")
    public Result<Void> deleteOrderById(@PathVariable("id") Integer orderId) {
        ordersService.removeById(orderId);
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }

    @GetMapping("/pay-order-again")
    @Operation(summary = "再次购买的实现逻辑")
    public Result<Void> payOrderAgain(@RequestParam("orderId") Integer orderId) {
        //根据orderId获取userId
        int userId = ordersService.getUserIdByOrderId(orderId);
        //根据orderId获取原订单的goodIds
        List<Map<String, Object>> goodIdsAndCount = orderItemsService.getGoodIdsAndCountByOrderId(orderId);
        Iterator<Map<String, Object>> iterator = goodIdsAndCount.iterator();
        //将商品id和用户id批量放回购物车。
        //将购物车里已有的进行合并先
        while (iterator.hasNext()) {
            Map<String, Object> goodIdAndCountMap = iterator.next();
            String goodId = (String) goodIdAndCountMap.get("goods_id");
            // 获取购物车中的对应商品
            Cart goodCart = cartService.getCartGoodByUserIdAndGoodId(userId, goodId);
            if (goodCart != null) {
                if (goodCart.getSelected() == 1) {
                    if (goodCart.getCount() < 10)
                        goodCart.setCount(goodCart.getCount() + 1);
                    cartService.saveOrUpdate(goodCart);
                    iterator.remove(); // 安全移除当前元素
                } else if (goodCart.getSelected() == 0) {
                    goodCart.setSelected(1);
                    cartService.saveOrUpdate(goodCart);
                    iterator.remove(); // 安全移除当前元素
                }
            }
        }
        if (!goodIdsAndCount.isEmpty()) {
            cartService.insertCartBatchByGoodIdsAndUserId(userId, goodIdsAndCount);
        }

        return Result.build(null, ResultCodeEnum.SUCCESS);
    }
}
